package util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpClientUtils {
    private static final CloseableHttpClient httpClient;
    private static final Logger logger=LoggerFactory.getLogger(HttpClientUtils.class);
    private static final Map<String,String> header=new HashMap<>();
    static {
        httpClient = HttpClientBuilder.create().build();
    }
    //构造url

    /**
     *
     * @param url  接口url
     * @param query_path  url后面的查询参数
     * @return  返回构造的url
     * @throws URISyntaxException  捕获异常
     */
    public static String build_url(String url, Map<String, String> query_path) throws URISyntaxException {
        URIBuilder uriBuilder = new URIBuilder(url);
        if (query_path != null) {
            for (String key : query_path.keySet()) {
                uriBuilder.addParameter(key, query_path.get(key));
            }
        }
        return uriBuilder.build().toString();
    }
    //构造响应数据
    public static ResponseData build_data(CloseableHttpResponse response) throws IOException {
        ResponseData responseData=new ResponseData();
        responseData.setCode(responseData.getCode());
        String data= EntityUtils.toString(response.getEntity());
        logger.info("data={}",data);
        if(data!=null && data.startsWith("{")){
            responseData.setBody(JSONObject.parseObject(data));
        }
        return responseData;
    }
    //构造响应头
    public static void build_header(String header_key,String header_value){
        header.put(header_key,header_value);
    }
    //封装get请求
    public static ResponseData get(String url,Map<String,String> query_path) throws URISyntaxException, IOException {
        String build_url = build_url(url, query_path);
        HttpGet httpGet=new HttpGet(build_url);
        logger.info("build_url={}",build_url);
        //设置请求头
        for(String key: header.keySet()){
            httpGet.setHeader(key, header.get(key));
        }
        CloseableHttpResponse response= httpClient.execute(httpGet);
        ResponseData responseData = build_data(response);
        response.close();
        return responseData;
    }
    public static ResponseData get(String url) throws IOException, URISyntaxException {
        return get(url, null);
    }
    //封装post-json
    public static ResponseData post_json(String url,Map<String,String> query_path,Map<String,Object> json_data) throws URISyntaxException, IOException {
        String build_url = build_url(url, query_path);
        logger.info("build_url={}",build_url);
        HttpPost httpPost=new HttpPost(build_url);
        //构造请求头
        for(String key: header.keySet()){
            httpPost.setHeader(key, header.get(key));
        }
        logger.info("请求头"+"headers={}",header);
        String data=JSONObject.toJSONString(json_data);
        logger.info("请求体"+"data={}",data);
        httpPost.setEntity(new StringEntity(data, ContentType.APPLICATION_JSON));
        CloseableHttpResponse response= httpClient.execute(httpPost);
        ResponseData responseData = build_data(response);
        response.close();
        return responseData;
    }
    public static ResponseData post_json(String url, Map<String, Object> json_data) throws IOException, URISyntaxException {
        return post_json(url,null,json_data);
    }
    public static ResponseData post_list(String url, List<Object> list) throws URISyntaxException, IOException {
        String build_url=build_url(url,null);
        HttpPost httpPost=new HttpPost(build_url);
        for(String key:header.keySet()){
            httpPost.setHeader(key, header.get(key));
        }
        logger.info("请求头"+"headers={}",header);
        String data=JSONObject.toJSONString(list);
        logger.info("请求体"+"data={}",data);
        httpPost.setEntity(new StringEntity(data,ContentType.APPLICATION_JSON));
        CloseableHttpResponse response= httpClient.execute(httpPost);
        ResponseData responseData=build_data(response);
        response.close();
        return responseData;
    }
    //上传文件  提交表单数据和上传文件

    /**
     *
     * @param url  构造的url
     * @param form_data  表单数据
     * @param file_params  文件数据
     * @return  返回响应对象
     * @throws IOException   捕获异常
     */
    public static ResponseData upload_file(String url,Map<String,String> form_data,Map<String,String> file_params) throws IOException {
        HttpPost httpPost=new HttpPost(url);
        //构建请求体数据
        MultipartEntityBuilder builder=MultipartEntityBuilder.create();
        //普通表单数据
        if(form_data!=null){
            for(String key: form_data.keySet()){
                builder.addPart(key,new StringBody(form_data.get(key),ContentType.MULTIPART_FORM_DATA));
            }
        }
        //设置文件数据  value文件的路径
        if(file_params!=null){
            for (String key: file_params.keySet()){
                builder.addBinaryBody(key,new File(file_params.get(key)));
            }
        }
        for(String key:header.keySet()){
            httpPost.setHeader(key, header.get(key));
        }
        HttpEntity reqEntity = builder.build();
        httpPost.setEntity(reqEntity);
        // 发送请求，并获取响应对象
        CloseableHttpResponse response = httpClient.execute(httpPost);
        // 构造响应数据
        ResponseData responseData = buildResponseData(response);
        // 释放资源
        response.close();
        return responseData;
    }

    private static ResponseData buildResponseData(CloseableHttpResponse response) throws IOException {
        ResponseData responseData = new ResponseData();
        // 响应状态码
        responseData.setCode(response.getStatusLine().getStatusCode());

        // 响应体数据
        String responseStr = EntityUtils.toString(response.getEntity());
        logger.info("responseStr={}", responseStr);
        // 判断是否为json数据
        if (responseStr != null && responseStr.startsWith("{")) {
            responseData.setBody(JSONObject.parseObject(responseStr));
        }
        return responseData;
    }
}
